package com.example.demo.dao;

import com.example.demo.dto.Department;
import com.example.demo.dto.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DepartmentMapper {

    @Autowired
    LogMapper logMapper;

    private static Map<Integer, Department> departmentMap = null;
    private Integer id = 106;

    static {
        departmentMap = new HashMap<Integer, Department>();
        departmentMap.put(101, new Department(101, "生化部门"));
        departmentMap.put(102, new Department(102, "生活部门"));
        departmentMap.put(103, new Department(103, "经济部门"));
        departmentMap.put(104, new Department(104, "事业部门"));
        departmentMap.put(105, new Department(105, "财务部门"));
    }

    public Collection<Department> getDepartmentDataList() {
        return departmentMap.values();
    }

    public Department getDepartmentById(Integer id) {
        return departmentMap.get(id);
    }

    public String insert(Department department) {
        try {
            Integer curId = id++;
            department.setId(curId);
            departmentMap.put(curId, department);
            log("数据插入", curId);
            return "操作成功";
        } catch (Exception e) {
            System.out.println(e.toString());
            return "数据存储异常";
        }
    }

    public String insertBatch(List<Department> departments) {
        try {
            departments.forEach(item -> {
                Integer curId = id++;
                item.setId(curId);
                departmentMap.put(curId, item);
                log("数据批量插入", curId);
            });
            return "操作成功";
        } catch (Exception e) {
            System.out.println(e.toString());
            return "数据批量存储异常";
        }
    }

    public String deleteById(Integer id) {
        try {
            departmentMap.remove(id);
            log("数据删除", id);
            return "操作成功";
        } catch (Exception e) {
            System.out.println(e.toString());
            return "数据删除异常";
        }
    }

    public String updateById(Department department) {
        try {
            Integer id = department.getId();
            departmentMap.remove(id);
            departmentMap.put(id, department);
            log("数据更新", id);
            return "操作成功";
        } catch (Exception e) {
            System.out.println(e.toString());
            return "数据更新失败";
        }
    }

    private void log(String operateType, Integer id) {
        Log log = new Log();
        log.setDataOrigin("部门信息");
        log.setOperateType(operateType);
        log.setOriginId(id);
        logMapper.insert(log);
    }
}
